package com.bawei.module_main.ui.splash


import android.graphics.BitmapFactory
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.view.Gravity
import android.view.View
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.Router
import com.bawei.lib_common.base.BaseActivity
import com.bawei.lib_common.base.BaseViewModel
import com.bawei.lib_common.getAttrValue
import com.bawei.lib_net.storage.AppMMKV
import com.bawei.module_main.R
import com.bawei.module_main.databinding.ActivitySplashBinding
import com.bawei.module_main.dialog.MessageNoticeDialog
import com.tencent.bugly.crashreport.CrashReport
import com.umeng.analytics.MobclickAgent
import com.umeng.commonsdk.UMConfigure


class SplashActivity : BaseActivity<BaseViewModel, ActivitySplashBinding>() {

    override val mLayoutResId: Int
        get() = R.layout.activity_splash

    override val mViewModel: BaseViewModel by viewModels()

    companion object {
        //最大延迟
        private const val SPLASH_MAX_DELAY: Long = 5_000
    }


    private val mHandler by lazy {
        object : Handler(Looper.getMainLooper()) {
            override fun handleMessage(msg: Message) {

                if (AppMMKV.needGuide) {
                    toGuide()
                } else {
                    toMain()
                }

            }
        }
    }

    //初始化结束后操作
    private var actionAfterInitFinished: (() -> Unit)? = null

    override fun initView() {

        val bitmap =
            BitmapFactory.decodeResource(resources, R.mipmap.icon_splash_img)

        // 创建圆角位图绘制
        val roundedDrawable = RoundedBitmapDrawableFactory.create(resources, bitmap)
        roundedDrawable.cornerRadius = 32f // 设置圆角半径（像素）

        mBinding.splashPic.setImageDrawable(roundedDrawable)
    }

    override fun initListener() {

    }

    override fun initData() {
        mBinding.countDownSkip.onSkipListener = {
            ARouter.getInstance().build(Router.Ui.GuideActivity).navigation()
        }



        //4:弹出对话框
        if (!AppMMKV.splashAgreement) {
            val colorMain = getAttrValue(this, com.bawei.lib_common.R.attr.colorTheme)
            val userAgreement = "《用户协议》"
            val privacyPolicy = "《隐私条款》"
            val content =
                "智慧园区非常尊重用户个人的信息保护，我们依据最新的监管要求特向您说明如下：\n1.在使用 APP过程中，我们有可能会收集、使用设备标识信息用于推送提醒消息。\n2.我们会一直采取严格的安全技术保护您的个人信息安全。\n3.未经您的同意，我们不会以协议约定之外的形式和渠道获取、共享或使用您的个人信息。\n您可通过阅读完整的${userAgreement}和${privacyPolicy}来了解详细信息。请您充分阅读并理解以上协议，点击同意按钮，即表示您已同意上述协议及以上约定。"
            val spannableStringBuilder = SpannableStringBuilder(content)
            val userAgreementStart = content.indexOf(userAgreement)
            val userAgreementEnd = userAgreementStart + userAgreement.length
            val privacyPolicyStart = content.indexOf(privacyPolicy)
            val privacyPolicyEnd = privacyPolicyStart + privacyPolicy.length

            spannableStringBuilder.setSpan(object : ClickableSpan() {
                override fun onClick(p0: View) {
//                    CommonWebActivity.jumpUserAgreement()
                    showToast("点击了用户")
                }

                override fun updateDrawState(ds: TextPaint) {
                    ds.color = ContextCompat.getColor(this@SplashActivity, com.bawei.lib_common.R.color.color_3298ff)
                    ds.isUnderlineText = false
                }

            }, userAgreementStart, userAgreementEnd, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)

            spannableStringBuilder.setSpan(object : ClickableSpan() {
                override fun onClick(p0: View) {
//                    CommonWebActivity.jumpPrivacyAgreement()
                    showToast("点击了隐私")
                }

                override fun updateDrawState(ds: TextPaint) {
                    ds.color = ContextCompat.getColor(this@SplashActivity, com.bawei.lib_common.R.color.color_3298ff)
                    ds.isUnderlineText = false
                }

            }, privacyPolicyStart, privacyPolicyEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

            MessageNoticeDialog(
                title = "温馨提示",
                message = spannableStringBuilder,
                alignment = Gravity.START,
                onConfirmClick = {
                    AppMMKV.splashAgreement = true
//                    mHandler.sendEmptyMessageDelayed(2, SPLASH_MAX_DELAY)
                    // 开始倒计时
                    mBinding.countDownSkip.startCountDown()
                    //第一次打卡：正式初始化
                    UMConfigure.init(this,"67170cee80464b33f6e18739","channel", UMConfigure.DEVICE_TYPE_PHONE,null)
                    CrashReport.initCrashReport(getApplicationContext(), "c0befbb921", true);
                    //事件埋点
                    val map: MutableMap<String, Any> = HashMap()
                    map["url"] = "123456" //广告链接
                    map["type"] = "1" //广告类型
                    MobclickAgent.onEventObject(this, "ad_click", map)
                },
                onCancelClick = {
                    finish()
                },
                confirmText = "同意",
                cancelText = "不同意",
                cancelable = false
            ).show(supportFragmentManager)

        } else {
//            mHandler.sendEmptyMessageDelayed(2, SPLASH_MAX_DELAY)
            mBinding.countDownSkip.startCountDown()
        }
    }

    fun toGuide() {
        ARouter.getInstance().build(Router.Ui.GuideActivity).navigation()
        actionAfterInitFinished?.invoke()
        finish()
    }

    fun toMain() {
        ARouter.getInstance().build(Router.Ui.MainActivity).navigation()
        actionAfterInitFinished?.invoke()
        finish()
    }

    override fun onResume() {
        super.onResume()
        MobclickAgent.onPageStart("Splash");
    }

    override fun onPause() {
        super.onPause()
        MobclickAgent.onPageEnd("Splash")
    }

}